#include"head.h"

int work(int local_socket)
{
    //脱离进程组
    printf("group id: %d-----", getpgrp());
    setpgid(0, 0);
    printf("group id: %d \n", getpgrp());


    while(1)
    {
        int net_fd;
        int flag;
        int ret; 
        recv_from_main(local_socket,&flag,&net_fd);
        printf("work.c:flag:%d\n",flag);

        //拿到与用户对应的socket缓冲区的指针对应的文件描述符
        if(flag==-1)
        {
            printf("\rworkc:exit:sig 2th is coming ,pid:%d  willgo  die!!!!\n\n",getpid());
            exit(0);
        }

        //程序收到运行指令
        //程序执行的是拷贝命令
        //实现send多种发送
        int epfd=epoll_create(1);
        ERROR_CHECK(epfd,-1,"epoll_create");

        struct epoll_event event;
        event.events=EPOLLIN;
        event.data.fd=net_fd;
        epoll_ctl(epfd,EPOLL_CTL_ADD,net_fd,&event);
        int lag=0;

        while(1)
        {
            struct epoll_event events[1024];
            int ready_num;

            ready_num=epoll_wait(epfd,events,1024,0);
            for(int i=0;i<ready_num;i++)
            {
                printf("\n\nwork.c:i:%d\n",i);

                lag=0;
                int size;
                ret=recv(net_fd,&size,sizeof(int),MSG_WAITALL);
                if(ret ==0)
                {
                    lag=1;
                    break;
                }
                printf("work.c:size:%d\n",size);


                char buf[60]={0};
                //recv
                ret=recvn(net_fd,buf,size);
                printf("work.c:ret:%d\n",ret);
                printf("work.c:buf:name:%s\n",buf);
                printf("----recved\n");

                //read\send

                int file_fd=open(buf,O_RDONLY);
                if(file_fd==-1)
                {
                    send(net_fd,"0",1,MSG_NOSIGNAL);
                    printf("no file\n");
                    continue;
                }
                else 
                    send(net_fd,"1",1,MSG_NOSIGNAL);
                printf("ready to send:work.c\n");
                struct stat stat;
                fstat(file_fd,&stat);

                send(net_fd,&stat.st_size,sizeof(off_t),MSG_NOSIGNAL);

                char buffer[1024]={0};

                while((ret=read(file_fd,buffer,1024))>0)
                {
                    int set =send(net_fd,buffer,ret,MSG_NOSIGNAL);
                    if(set ==-1)
                    {
                        printf("work.c:client exit\n");
                        lag=1;
                        break;
                    }
                }
                if(lag==1) break;
                printf("send done:work.c\n");
                close(file_fd);
            }
            if(lag==1)
            {
                printf("客户端已经中断\n");
                break;
            }
        }
        close(net_fd);
        //给main.c发送信息
        send(local_socket,"done",4,MSG_NOSIGNAL);
    }
        return 0;
    }




